package com.mdp.tpa.pay.alipay.ctrl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.utils.BaseUtils;
import com.mdp.core.utils.RequestUtils;
import com.mdp.micro.client.CallBizService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.tpa.pay.alipay.service.AlipayService;
import com.mdp.tpa.pay.cm.entity.Orders;
import com.mdp.tpa.pay.cm.entity.UniOrder;
import com.mdp.tpa.pay.cm.client.AcPaymentPushService;
import com.mdp.tpa.pay.cm.service.OrdersService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController("mall.tpa.alipay.AlipayController")
@RequestMapping(value="/**/pay/alipay")
@Log
public class AlipayController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    AlipayService alipayService;

    @Autowired
    CallBizService callBizService;


    @Autowired
    AcPaymentPushService acPaymentPushService;

    @Value("${mdp.api-gate:http://gate}")
    String apiGate="";//http://localhost:7041

    /**
     * 调用统一下单接口，生成预支付交易单
     * 微信支付要求：除被扫支付场景以外，商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易回话标识后再按扫码、JSAPI、APP等不同场景生成交易串调起支付
     */
    @RequestMapping(value="/uniOrder",method= RequestMethod.POST)
    public Map<String,Object> unifiedorder(@RequestBody UniOrder order) {
        User user= LoginUtils.getCurrentUserInfo();
        Orders orders = ordersService.getOrders(order);
        if(orders==null){
            return Result.error("orders-is-not-exists","订单不存在");
        }else if(!orders.getUserid().equals(user.getUserid())){
            return Result.error("orders-is-not-yours","订单不属于您的");
        }else if("3".equals(orders.getOrderStatus())||"1".equals(orders.getPayStatus())){
            return Result.error("orders-had-pay","订单已支付");
        }else if(!"0".equals(orders.getPayStatus()) && !"2".equals(orders.getOrderStatus())){
            return Result.error("orders-not-in-pay","订单暂未需要支付");
        }else {
            Tips tips=new Tips("下单成功");
            Map<String,Object> m=new HashMap<>();
            m.put("tips",tips);
            Map<String,Object> data=new HashMap<>();
            try {
                String payId= UUID.randomUUID().toString();
                AlipayTradePagePayResponse response=this.alipayService.uniOrder(order.getOtype(),orders.getId(),payId, orders.getPayAt(),orders.getName(),order.getReturnUrl());


                log.info("alipay-response 返回结果"+JSON.toJSONString(response));
                if(response.isSuccess()){
                    String spbillCreateIp= RequestUtils.getIpAddr(RequestUtils.getRequest());



                    //更新订单preId
                    Orders ordersUpdate=new Orders(orders.getId());
                    ordersUpdate.setOtype(order.getOtype());
                    if(!StringUtils.hasText(response.getTradeNo())){
                        ordersUpdate.setPrepayId(payId);
                    }else {
                        ordersUpdate.setPrepayId(response.getTradeNo());
                    }

                    ordersUpdate.setPrepayTime(new Date());
                    ordersUpdate.setPayId(payId);
                    ordersUpdate.setPayType("2");
                    ordersService.updatePrepayId(ordersUpdate);

                    Map<String,Object> pushOrders=BaseUtils.toMap(orders);
                    pushOrders.put("action","createOrder");
                    pushOrders.put("ip",spbillCreateIp);
                    pushOrders.put("payId",payId);
                    pushOrders.put("prepayId",ordersUpdate.getPrepayId());
                    pushOrders.put("otype",orders.getOtype());
                    pushOrders.put("prepayTime",ordersUpdate.getPrepayTime());
                    pushOrders.put("payType",ordersUpdate.getPayType());
                    if("5".equals(order.getOtype())){
                        acPaymentPushService.pushRechargeOrders(pushOrders );
                    }else{
                        acPaymentPushService.pushPaymentOrders(pushOrders );
                    }


                    data.put("htmlStr",response.getBody());
                    m.put("data",data);
                }else{
                    return Result.error("uni-order-un-success","下单失败");
                }
            }catch (BizException be){
                return Result.error(be);
            }catch (Exception e){
                return Result.error("uni-order-un-success",e.getMessage());
            }
            return m;
        }

    }
}
